import time
import uuid

from django.db import models
from django.contrib.auth.models import AbstractUser
# 模型

# 账号信息
from django.templatetags.tz import localtime
from django.utils import timezone
from django.utils.timezone import now, timedelta


# #APP应用类型表
class AppType(models.Model):
    id = models.BigAutoField(primary_key=True)  # 主键，bigint
    apptype = models.CharField(max_length=20, verbose_name='APP类型')
    appname = models.CharField(max_length=32, null=True, verbose_name="APP名称")
    appdsc = models.TextField(verbose_name='备注', null=True)

    class Meta:
        verbose_name = 'APP类型表'
        verbose_name_plural = verbose_name


class UserInfo(AbstractUser):
    phone = models.CharField(max_length=11, verbose_name='手机号', null=True)
    real_name = models.CharField(max_length=32, null=True, verbose_name="姓名")
    last_login = models.DateTimeField(blank=True, verbose_name='最后登录时间', null=True)
    date_joined = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    # 2024-09-09 新增有效期和ip,pcmac
    last_login_ip = models.GenericIPAddressField(null=True, verbose_name='最后登录ip', blank=True)
    pcmac = models.TextField(verbose_name='设备MAC地址', null=True)
    end_data = models.DateTimeField(verbose_name='用户到期时间', null=True)
    apptype = models.ForeignKey("AppType", on_delete=models.CASCADE, default=1)

    class Meta:
        verbose_name = '用户管理表'
        verbose_name_plural = verbose_name
        db_table = 'user'

    def __str__(self):
        return self.username


# 验证码信息
class Redis(models.Model):
    email = models.CharField(max_length=30, verbose_name='邮箱', null=True)
    msmcode = models.CharField(max_length=6, verbose_name='验证码', null=True)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    expires_at = models.DateTimeField(verbose_name='过期时间', null=True)

    class Meta:
        verbose_name = '验证信息表'
        verbose_name_plural = verbose_name

    # 重写 save 方法，在每次保存时设置 expires_at
    def save(self, *args, **kwargs):
        if not self.expires_at:  # 只有在 expires_at 为空时设置
            # 确保 created_at 不为 None
            if self.created_at is None:
                self.created_at = timezone.now()
            self.expires_at = self.created_at + timedelta(minutes=3)
        super(Redis, self).save(*args, **kwargs)

    def is_expired(self):
        return self.expires_at <= timezone.now()


# 网站一级菜单
class FirstMenu(models.Model):
    firstmenu = models.CharField(max_length=20, verbose_name='一级菜单')
    iconclass = models.CharField(max_length=20, verbose_name='图标Class', null=True)
    iframesrc = models.TextField(verbose_name='Url地址', null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        verbose_name = '一级菜单管理'
        verbose_name_plural = verbose_name


# 网站二级菜单
class SecondMenu(models.Model):
    secondmenu = models.CharField(max_length=20, verbose_name='二级菜单')
    iconclass = models.CharField(max_length=20, verbose_name='图标Class', null=True)
    firstmenu = models.ForeignKey("FirstMenu", on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        verbose_name = '二级菜单管理'
        verbose_name_plural = verbose_name


# 网站三级菜单
class ThirdMenu(models.Model):
    thirdmenu = models.CharField(max_length=20, verbose_name='三级菜单')
    iframesrc = models.TextField(verbose_name='Url地址')
    secondmenu = models.ForeignKey("SecondMenu", on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        verbose_name = '三级菜单管理'
        verbose_name_plural = verbose_name


# 参数配置表
class Config(models.Model):
    para = models.CharField(max_length=50, verbose_name='参数名称', null=False, primary_key=True)
    desc = models.CharField(max_length=50, verbose_name='参数描述', null=False)
    value = models.TextField(verbose_name='参数值', null=False)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        verbose_name = '参数配置表'
        verbose_name_plural = verbose_name


# 聊天记录表
class ChartLog(models.Model):
    username = models.ForeignKey("UserInfo", on_delete=models.CASCADE)
    question = models.TextField(verbose_name='提问', null=False)
    answer = models.TextField(verbose_name='回答')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        verbose_name = '聊天记录表'
        verbose_name_plural = verbose_name


# 电子书源网址
class EbookSrc(models.Model):
    srcid = models.BigAutoField(primary_key=True)  # 主键，bigint
    srcname = models.CharField(max_length=200, verbose_name='书源名称')  # 书源名称，varchar(200)
    srcurl = models.CharField(max_length=200, verbose_name='书源网址')  # 书源网址，varchar(200)
    listurl = models.CharField(max_length=200, verbose_name='书列表url')  # 书列表url，varchar(200)

    class Meta:
        db_table = 'ebook_src'
        verbose_name = '书源网址'
        verbose_name_plural = 'e_书源网址'

    def __str__(self):
        return self.srcname


#  电子书分类
class EbookType(models.Model):
    typeid = models.BigAutoField(primary_key=True)  # 主键，bigint
    name = models.CharField(max_length=100, verbose_name='电子书分类')  # 类型名称

    class Meta:
        db_table = 'ebook_type'
        verbose_name = '电子书分类'
        verbose_name_plural = 'e_电子书分类'

    def __str__(self):
        return self.name


# 电子书库
class EbookStore(models.Model):
    storeid = models.BigAutoField(primary_key=True, db_index=True)  # 主键，bigint
    srcid = models.IntegerField(default=1, verbose_name='书源id')  # 关联表id， 书源表id
    typeid = models.IntegerField(default=1, verbose_name='分类id')  # 关联表id， 书籍分类表id
    bookno = models.CharField(max_length=200, verbose_name='书籍编号')  # 书籍编号，varchar(200)
    bookname = models.CharField(max_length=200, verbose_name='书籍名称')  # 书籍名称，varchar(200)
    bookstatus = models.CharField(max_length=200, verbose_name='书籍状态')  # 书籍状态，varchar(200)
    bookimg = models.TextField()  # 封面，longtext
    booknum = models.CharField(max_length=200, verbose_name='总字数')  # 总字数，int，默认值为0
    auto = models.CharField(max_length=200, verbose_name='作者')  # 作者，varchar(200)
    update = models.DateField(verbose_name='上架时间')  # 上架时间，date
    score = models.FloatField(verbose_name='评分')  # 评分，float
    booksyno = models.TextField(verbose_name='书籍简介')  # 书籍简介，longtext
    bookdetail = models.TextField(verbose_name='书籍详情')  # 书籍详情，longtext
    clicktime = models.DateTimeField(null=True, blank=True, verbose_name='最近点击时间')  # 最近点击时间，datetime
    clicknum = models.IntegerField(default=0, verbose_name='点击次数')  # 点击次数，int，默认值为0
    addtime = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')  # 创建时间，默认值为当前时间

    class Meta:
        db_table = 'ebook_store'
        verbose_name = '电子书城'
        verbose_name_plural = 'e_电子书城'

    def __str__(self):
        return self.bookname


# 电子书章节表
class EbookChapter(models.Model):
    id = models.BigAutoField(primary_key=True)  # 主键，bigint
    storeid = models.IntegerField(default=1, verbose_name='书库id')  # 关联表id， 书库表id
    srcid = models.IntegerField(default=1, verbose_name='书源id')  # 关联表id，  书源表id
    typeid = models.IntegerField(default=1, verbose_name='分类id')  # 关联表id， 书籍分类表id
    chapurl = models.CharField(max_length=200, verbose_name='章节url')  # 章节url，varchar(200)
    chapternum = models.IntegerField(verbose_name='章节数')  # 章节数，int
    chaptertitle = models.CharField(max_length=200, verbose_name='章节标题')  # 章节标题，varchar(200)
    content = models.TextField(verbose_name='章节内容')  # 章节内容，longtext
    addtime = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')  # 创建时间，默认值为当前时间

    class Meta:
        db_table = 'ebook_chapter'
        index_together = [('storeid', 'chapternum'), ]
        verbose_name = '电子书章节'
        verbose_name_plural = 'e_电子书章节'

    def __str__(self):
        return f'{self.chaptertitle}'


# 视频上传工具证书有效期表
class VideoTool(models.Model):
    id = models.BigAutoField(primary_key=True)  # 主键，bigint
    pcmac = models.TextField(verbose_name='设备MAC地址', null=False)
    date_end = models.DateTimeField(verbose_name='有效期结束时间', null=True)

    class Meta:
        verbose_name = '视频上传工具证书有效期表'
        verbose_name_plural = verbose_name


def generate_order_id():
    """生成订单 ID：毫秒级时间戳 + UUID"""
    timestamp = int(time.time() * 1000)  # 获取毫秒级时间戳(13位)
    unique_id = uuid.uuid4().hex[:19]  # 获取去掉分隔符的 UUID
    return f"{timestamp}{unique_id}"


class OrderInfo(models.Model):
    # 订单ID：确保32位唯一ID，包含时间戳和 UUID
    order_id = models.CharField(
        max_length=50, unique=True, default=generate_order_id, editable=False, db_index=True
    )  # 添加索引

    # 支付类型：微信支付(WX) 或 支付宝支付(ZFB)
    PAY_TYPE_CHOICES = [
        ('WX', '微信'),
        ('ZFB', '支付宝'),
    ]
    pay_type = models.CharField(max_length=3, choices=PAY_TYPE_CHOICES, verbose_name="支付类型")
    PAY_WAY_CHOICES = [('PC', '电脑端'),('PHONE', '移动端'),]
    pay_way = models.CharField(max_length=20, choices=PAY_WAY_CHOICES, verbose_name="支付端")
    pay_name = models.CharField(max_length=20, verbose_name="支付应用")
    pay_days = models.CharField(max_length=20, verbose_name="购买天数")
    # 支付交易号：由支付平台返回
    trade_id = models.CharField(max_length=64, blank=True, null=True, verbose_name="支付交易号")

    # 创建时间：记录订单创建时间
    create_time = models.DateTimeField(default=now, verbose_name="创建时间")

    # 支付金额：保留两位小数
    pay_sum = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="支付金额")

    # 用户支付账号
    user_name = models.CharField(max_length=128, verbose_name="支付账号", db_index=True)  # 添加索引

    # 支付状态：未支付、支付中、支付成功、支付失败
    STATUS_CHOICES = [
        ('PENDING', '未支付'),
        ('SUCCESS', '支付成功'),
        ('FAILED', '支付失败'),
        ('REFUNDED', '已退款'),
    ]
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='PENDING', verbose_name="支付状态")

    # 支付时间：支付成功后的时间
    pay_time = models.DateTimeField(blank=True, null=True, verbose_name="支付时间")

    # 商品描述：用户支付商品信息
    description = models.TextField(blank=True, verbose_name="商品描述")

    # IP 地址：用户发起支付时的 IP 地址
    user_ip = models.GenericIPAddressField(blank=True, null=True, verbose_name="用户IP")

    # 备注：用于管理员记录订单备注
    remark = models.TextField(blank=True, verbose_name="备注")

    class Meta:
        verbose_name = "订单信息"
        verbose_name_plural = "订单信息"
        ordering = ['-create_time']
        indexes = [
            models.Index(fields=['order_id']),  # 为 order_id 添加显式索引（冗余但清晰）
            models.Index(fields=['user_name']),  # 为 user_name 添加显式索引
        ]

    def __str__(self):
        return f"订单 {self.order_id} - {self.get_status_display()}"

    @property
    def formatted_create_time(self):
        """格式化创建时间为 '年月日时分秒'"""
        return localtime(self.create_time).strftime('%Y-%m-%d %H:%M:%S')

    @property
    def is_paid(self):
        """检查订单是否已支付"""
        return self.status == 'SUCCESS'
